package com.bwie.service.impl;

import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.pojo.Menu;
import com.bwie.pojo.User;
import com.bwie.service.UserService;
import com.bwie.mapper.UserMapper;
import com.bwie.utils.R;
import com.bwie.utils.Result;
import com.bwie.vo.UserPageVo;
import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.google.zxing.PlanarYUVLuminanceSource;
import io.jsonwebtoken.Jwts;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;

/**
 * @author 陶仕豪
 * @description 针对表【tb_user(用户表)】的数据库操作Service实现
 * @createDate 2025-05-21 15:38:29
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {
    @Autowired
    UserMapper userMapper;

    @Autowired
    FastFileStorageClient fastFileStorageClient;

    @Override
    public Result getMenuTree(HttpServletRequest request) {
        //获取用户ID
        String token = request.getHeader("token");
        if (token == null) {
            return Result.error().setMsg("token为空");
        }
        Integer userId = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody().get("userId", Integer.class);


        List<Menu> list = userMapper.getMenuTree(userId);
        List<Tree<String>> treeList = TreeUtil.build(list, "0", (menu, tree) -> {
            tree.setName(menu.getMenuName());
            tree.setParentId(menu.getMenuPid() + "");
            tree.setId(menu.getMenuId() + "");
            tree.putExtra("path", menu.getMenuPath());
        });
        return Result.ok().setData(treeList);
    }

    @Override
    public Result getUserList(UserPageVo userPageVo) {
        Page<User> userPage = new Page<>(userPageVo.getPageNum(), userPageVo.getPageSize());
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(userPageVo.getKeyWord())) {
            wrapper.lambda().like(User::getUserName, userPageVo.getKeyWord())
                    .or().like(User::getNickName, userPageVo.getKeyWord())
                    .or().like(User::getUserMobile, userPageVo.getKeyWord())
                    .or().like(User::getUserEmail, userPageVo.getKeyWord());
        }
        if (userPageVo.getGender() != null) {
            wrapper.lambda().eq(User::getGender, userPageVo.getGender());
        }
        if (StringUtils.isNotEmpty(userPageVo.getStartTime())) {
            wrapper.lambda().ge(User::getCreateTime, userPageVo.getStartTime());
        }
        if (StringUtils.isNotEmpty(userPageVo.getEndTime())) {
            wrapper.lambda().le(User::getCreateTime, userPageVo.getEndTime());
        }
        Page<User> page = userMapper.selectPage(userPage, wrapper);
        return Result.ok().setData(page);
    }

    @Override
    public Result amendUser(User user) {
        userMapper.updateById(user);
        return Result.ok();
    }

    @Override
    public Result upload(MultipartFile file) {
        try {
            String extName = FileNameUtil.extName(file.getOriginalFilename());
            StorePath storePath = fastFileStorageClient.uploadFile(file.getInputStream(), file.getSize(), extName, null);
            String url = "http://192.168.80.192:8888/" + storePath.getFullPath();
            return Result.ok().setData(url);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error().setMsg("上传失败");
        }
    }

    @Override
    public Result deleteUser(Integer userId) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            return Result.error().setMsg("该用户不存在");
        }
        userMapper.deleteById(userId);
        return Result.ok();
    }

    @Override
    public Result deleteUserAll(List<User> userList) {
        if (userList == null || userList.size() == 0) {
            return Result.error().setMsg("该用户不存在");
        }
        for (User user : userList) {
            userMapper.deleteById(user.getUserId());
        }
        return Result.ok();
    }

    @Override
    public Result checkUser(User tbUser) {
        if (tbUser.getUserStatus() == 2) {
            if (StringUtils.isEmpty(tbUser.getReason())) {
                return Result.error().setMsg("请填写驳回原因");
            }
        }
        User user = userMapper.selectById(tbUser.getUserId());
        if(user==null){
            return Result.error().setMsg("商户不存在");
        }
        //审核
        user.setUserStatus(tbUser.getUserStatus());
        user.setReason(tbUser.getReason());

        userMapper.updateById(user);
        return Result.ok();
    }
}




